// 首先引入axios和上一步封装的cookie方法

import type {
  AxiosInstance,
  AxiosRequestConfig,
  AxiosResponse,
  AxiosPromise,
  AxiosError,
} from "axios";
// 是否显示重新登录
export let isRelogin = { show: false };
import cache from "/@ts/plugins/cache";
import fileSaver from "file-saver";
import { routerPush } from '/@ts/hooks/route'
import axios from "axios";
import { ElMessage, ElMessageBox, ElNotification,ElLoading } from "element-plus";
import { router } from "/@ts/router";
import { enumStatus } from "/@ts/axios/config";
import errorCode from "/@ts/axios/errorCode";
import { getToken } from "/@ts/hooks/cookie";
import formatTool from "/@ts/hooks/format";
const { tansParams } = formatTool();
import { useLoginStore } from "../store/modules/login";
 
export class Interceptors {
  instance: AxiosInstance;
  loading:any;
  constructor() {
    this.instance = axios.create({
      baseURL: import.meta.env.VITE_BASE_URL as string,
      timeout: 50000,
    });
  }
  // 初始化拦截器
  init() {
    // 请求接口拦截器
   
    this.instance.interceptors.request.use(
      (config: AxiosRequestConfig) => {
       
        // 是否需要设置 token
        const isToken = (config.headers || {}).isToken === false;
        const isloading = (config.headers || {}).isToken === false;
        if(!isloading){
          this.loading = ElLoading.service({
            lock: true,
            text: '加载中.....',
            background: 'rgba(0, 0, 0, 0.7)',
          })
        }
    
        if (getToken() && !isToken) {
          config.headers["Authorization"] = "Bearer " + getToken(); // 让每个请求携带自定义token 请根据实际情况自行修改
        }
        // get请求映射params参数
        if (config.method === "get" && config.params) {
          let url = config.url + "?" + tansParams(config.params);
          url = url.slice(0, -1);
          config.params = {};
          config.url = url;
        }
        config.headers["Type"] = "pc";
        config.headers["Content-Type"] = "application/json;charset=utf-8";

        if (
          config.method === "post" ||
          config.method === "POST" ||
          config.method === "put" ||
          config.method === "PUT" ||
          config.method === "delete" ||
          config.method === "DELETE"
        ) {
          if (config.data instanceof FormData) {
            config.headers["Content-Type"] =
              "multipart/form-data; charset=UTF-8";
          } else {
            if (!config.data) {
              config.data = {};
            }
            config.headers["Content-Type"] = "application/json;charset=utf-8";
            // var dd = qs.stringify(config.data)
            // config.data = dd
          }
        }
        // 是否需要防止数据重复提交
        const isRepeatSubmit = (config.headers || {}).repeatSubmit === false;
        if (
          !isRepeatSubmit &&
          (config.method === "post" || config.method === "put")
        ) {
          const requestObj = {
            url: config.url,
            data:
              typeof config.data === "object"
                ? JSON.stringify(config.data)
                : config.data,
            time: new Date().getTime(),
          };
          const sessionObj = cache.session.getJSON("sessionObj");
          if (
            sessionObj === undefined ||
            sessionObj === null ||
            sessionObj === ""
          ) {
            cache.session.setJSON("sessionObj", requestObj);
          } else {
            const s_url = sessionObj.url; // 请求地址
            const s_data = sessionObj.data; // 请求数据
            const s_time = sessionObj.time; // 请求时间
            const interval = 1000; // 间隔时间(ms)，小于此时间视为重复提交
            if (
              s_data === requestObj.data &&
              requestObj.time - s_time < interval &&
              s_url === requestObj.url
            ) {
              const message = "数据正在处理，请勿重复提交";
              console.warn(`[${s_url}]: ` + message);
              return Promise.reject(new Error(message));
            } else {
              cache.session.setJSON("sessionObj", requestObj);
            }
          }
        }
        return config;
      },
      (err: AxiosError) => {
        console.error(err);
      },
    );

    // 响应拦截器 -1报错，-99服务器错误。-2登录失效，-3 无访问权限
    this.instance.interceptors.response.use(
      (response: AxiosResponse) => {
        const    loginStore = useLoginStore()
        if(this.loading){
          this.loading.close();
        }
        const code = response.data.code || 200;
        // 未设置状态码则默认成功状态
        // 获取错误信息
        const msg = errorCode[code] || response.data.msg || errorCode["default"];
        // 对响应数据做点什么
       
        const {config} = response
     
        if (code === 401) {
          if (!isRelogin.show) {
            isRelogin.show = true;
            ElMessageBox.confirm(
              "登录状态已过期，您可以继续留在该页面，或者重新登录",
              "系统提示",
              {
                confirmButtonText: "重新登录",
                cancelButtonText: "取消",
                type: "warning",
              },
            )
              .then(() => {
                isRelogin.show = false;
                loginStore.LogOut().then(() => {
                  routerPush({ path: "/login" });
                  // setTimeout(() => {
                  //   location.reload();
                  // }, 100);
                });
              })
              .catch(() => {
                isRelogin.show = false;
              });
          }
          return Promise.reject("无效的会话，或者会话已过期，请重新登录。");
        } else if (code === 500) {
          ElMessage({ message: msg, type: "error" });
          return Promise.reject(new Error(msg));
        } else if (code === 601) {
          ElMessage({ message: msg, type: "warning" });
          return Promise.reject("error");
        } else if (code !== 200) {
          ElNotification.error({ title: msg });
          return Promise.reject("error");
        } else {
          //消息提现操作
     
          if(config.method!='get'&&config.showMessage){
            ElMessage({ message: msg, type: "success" });
          }
          return response.data;
        }
      },
      (err: AxiosError) => {
        isRelogin.show = false;
        // if (err.message === "Request failed with status code 500") {
        //   console.error('系统错误，请检查API是否正常！');
        //   return;
        // }
        if (enumStatus.goLoginArr.includes(err.response.data.status)) {
          ElMessage.error(err.response.data.msg);
          routerPush({ path: "/login" });
        }

        // const err2 = { errCode: -110, errMsg: err.message || "Error" };
        return Promise.reject(err);
      },
    );
  }
  // 返回一下
  getInterceptors() {
    this.init();
    return this.instance;
  }
}

// 请求配置
export class HttpServer {
  axios: any;
  // 获取axios实例
  constructor() {
    this.axios = new Interceptors().getInterceptors();
  }
  // 简单封装一下方法
  request(config: any): AxiosPromise {
    return this.axios(Object.assign(config, { showMessage: true },config));
  }
}

const http = new HttpServer();

export default http;
